package com.jgp.glmeeting.mobile.controller;

import com.alibaba.fastjson.JSON;
import com.jgp.glmeeting.mobile.commons.BaseResponse;
import com.jgp.glmeeting.mobile.commons.ErrorMsg;
import com.jgp.glmeeting.mobile.commons.HttpGetUtil;
import com.jgp.glmeeting.mobile.commons.WxConfig;
import com.jgp.glmeeting.model.Manager;
import com.jgp.glmeeting.model.Participants;
import com.jgp.glmeeting.service.ManagerService;
import com.jgp.glmeeting.service.ParticipantsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mobile/LoginController")
public class MobileLoginController {

    private final Logger logger = LoggerFactory.getLogger(MobileLoginController.class);

    @Autowired
    private ParticipantsService participantsService;

    @Autowired
    private ManagerService managerService;

    @RequestMapping("/login")
    public BaseResponse login(String code) {
        if (StringUtils.isBlank(code)) {
            return new BaseResponse(ErrorMsg.INVALID_PARAM.getCode(), ErrorMsg.INVALID_PARAM.getErrorMsg());
        }

        //拼接参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("secret", WxConfig.secret);
        params.put("appid", WxConfig.appid);
        params.put("grant_type", WxConfig.grantType);
        params.put("js_code", code);
        String result = HttpGetUtil.httpRequestToString(
                "https://api.weixin.qq.com/sns/jscode2session", params);
        System.out.println("result:" + result);
        Map<String, Object> returnMap = JSON.parseObject(result, Map.class);
        if (returnMap == null) {
            return new BaseResponse(ErrorMsg.GET_WE_USER_INFO_FAIL.getCode(), ErrorMsg.GET_WE_USER_INFO_FAIL.getErrorMsg());
        }
        Object errcode = returnMap.get("errcode");
        if (errcode != null) {
            return new BaseResponse(Integer.parseInt(errcode.toString()), returnMap.get("errmsg").toString());
        }
        try {
            String openId = returnMap.get("openid").toString();//获取对应返回的客户的openid
            //根据openid 返回参会人
            Participants participants = participantsService.queryParticipantsByOpenId(openId);
            //我自己加的根据openid返回会议总管//
            Manager manager=managerService.queryManagerByMobilePhone(openId);
            Map<String, Object> map = new HashMap<>();
            map.put("openId", openId);
            map.put("participants", participants);
            map.put("manager",manager);
            BaseResponse response = new BaseResponse(200);
            response.setObj(map);
            return response;
        } catch (Exception e) {
            logger.error("小程序登录失败", e);
            return new BaseResponse(ErrorMsg.SERVER_ERROR.getCode(), ErrorMsg.SERVER_ERROR.getErrorMsg());
        }

    }

    /**
     * openId跟用户绑定
     *
     * @param openId
     * @param mobilePhone
     * @return
     */
    @RequestMapping("bindParticipants")
    public BaseResponse bindParticipants(String openId, String mobilePhone) {
        if (StringUtils.isBlank(openId) || StringUtils.isBlank(mobilePhone)) {
            return new BaseResponse(ErrorMsg.INVALID_PARAM.getCode(), ErrorMsg.INVALID_PARAM.getErrorMsg());
        }
        //我加的代码


            if(participantsService.queryParticipantsBymobilePhone(mobilePhone)!=null){
            return participantsService.bindParticipants(openId, mobilePhone);}else
            if(managerService.queryManagerByMobilePhone(mobilePhone)!=null){
                return managerService.bindManager(openId,mobilePhone);
            }else{

           // logger.error("小程序openId跟用户绑定失败", e);
            return new BaseResponse(ErrorMsg.GET_PARTICIPANTS_FAIL_BY_MOBILEPHONE.getCode(), ErrorMsg.GET_PARTICIPANTS_FAIL_BY_MOBILEPHONE.getErrorMsg());}

    }
}
